Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

317
Vistas
How can I refresh JWT token every "t" minutes?

I am trying to implement an auto refresh for access-token every "t" minutes; I implemented a setInterval in useEffect (in the root component), which sends a request for a new access-token. When I run the code, at times the interval begins onMount and other times it does not run at all.

Another problem I am having that when I redirect the user to the login page, I try to clear the interval and it continues running even after clearInterval.

If there is any other way to implement JWT refresh tokens at set intervals of time, I am open to them too.

 useEffect(() => {
      async function getRefreshToken() {
        const response = await axios.post("http://localhost:3001/refreshToken", {refreshToken}, {withCredentials: true})
        if (response.data.redirect) {
          clearInterval(refresh)
          history.replace(`${response.data.redirect}`)
          localStorage.clear()
        }} 

      const refresh = setInterval(getRefreshToken, 4000)
    }, [])
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here is a working codesandbox example. You can change the functions to match your case

Explanation

What you want is a ref to store the interval to clear it outside of useEffect. You can set the interval just like you do inside useEffect, and save the interval inside the ref:

const ref = useRef()

useEffect(() => {
   const interval = setInterval(...)
   ref.current = interval
}, [])

You need to use a cleanup function inside useEffect to avoid memory leaks:

useEffect(() => {
   const interval = setInterval(...)
   ref.current = interval
   return () => clearInterval(interval)
}, [])

Then, you can clear the interval whenever using :

clearInterval(ref.current)

Remember to use useCallback hook on your axios call function to make sure react doesn't unnecessarily renders.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda